// 用于处理主进程和渲染进程的通信
import useAppStore from "@/store/modules/appInfos";

let appStore = null;
let ipc = null;
// 用于处理shell
let shell = null;

// 初始化ipc
export function ipcInit() {
    try {
        console.log('init ipcRenderer');
        appStore = useAppStore();
        const electron = window.require('electron');
        ipc = electron.ipcRenderer;
        shell = electron.shell;
        appStore.setIpc(ipc);
        appStore.setShell(shell);
    } catch (e) {
        console.error('failed to init ipcRenderer',e);
    }
}

// 显示主窗口
export function windowShow() {
    ipcSend('window-show')
}

// 窗口最小化
export function windowMin() {
    ipcSend('window-min');
}

//窗口最大化
export function windowMax() {
    ipcSend('window-max');
}

//窗口还原
export function windowRestore() {
    ipcSend('window-restore');

}

// 主页面关闭按钮使用退出程序
export function windowQuit() {
    ipcSend("window-quit");

}

/**
 * Opens the browser
 * @param url
 */
export function openBrowser(url) {
    //判断url的要求https/http，不合格的进行补全
    if (url.indexOf("http://") === -1 && url.indexOf("https://") === -1) {
        url = "http://" + url;
    }

    if (shell) {
        shell.openExternal(url);
    } else {
        window.open(url);
    }
}


//通用的发送消息方法
export function ipcSend(message, args) {
    if (ipc) {
        ipc.send(message, args)
    } else {
        console.log(message + " ipc is null")
    }
}

//通用的发送消息方法同步返回
export function ipcSendSync(message, args) {
    if (ipc) {
        return ipc.sendSync(message, args)
    } else {
        console.log(message + " ipc is null")
        return null
    }
}

//electron-store的操作
export function electronStoreGet(key) {
    return ipcSendSync('electronStoreGet', key);
}

export function electronStoreSet(key, value) {
    let args = {
        name: key,
        val: value
    }


    ipcSend('electronStoreSet', args);
}

export function electronStoreRemove(key) {
    //todo
    ipcSend('electronStoreRemove', key)
}

//日志输出 info
export function loggerInfo(message, args) {
    if (args) {
        message = message + JSON.stringify(args)
    }
    if (ipc) {
        ipcSend('logger-info', message)
    }
}


//主窗口聚焦
export function mainWindowsShow() {
    ipcSend('mainWindowsShow')
}


// 关闭窗口
export function windowCloseToTray() {
    ipcSend('window-close-to-tray');
}
